package edu.hawaii.halealohacli.command;

import java.text.SimpleDateFormat;
import java.util.Locale;
import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.client.WattDepotClient;
import org.wattdepot.resource.source.jaxb.Source;

/**
 * Defines the current-power command for hale-aloha-cli-chair.
 * 
 * @author Chris Wilson
 * @author Chris Fang
 */
public class CurrentPower implements Command {
  private String name, description, usage, input;
  private WattDepotClient client;
  private SourceData dataModule;
  private double pwrReading;

  /**
   * Creates an instance of this command with the client set to null by default, requiring
   * initialization.
   */
  public CurrentPower() {
    this.name = "current-power";
    this.usage = "current-power [tower | lounge]";
    this.description = "Returns the current power in kW for the associated tower or lou nge.";
  }

  /**
   * Initializes this command with a healthy WattDepot client.
   * 
   * @param client A healthy WattDepot client used to initialize the command
   * @param args Arguments required by the command for execution
   * @return Whether or not the arguments passed was accepted by the command initialization
   */
  @Override
  public boolean initializeCommand(WattDepotClient client, String[] args) {
    this.client = client;
    if (args.length != 2) {
      System.out.format("The arguments are invalid " + "(Enter \"help\" to see command usage");
      return false;
    }
    this.input = args[1];
    return true;
  }

  /**
   * Returns the name of this command.
   * 
   * @return the name of this command
   */
  @Override
  public String getName() {
    return this.name;
  }

  /**
   * Returns the usage syntax of this command.
   * 
   * @return the usage syntax of this command
   */
  @Override
  public String getUsage() {
    return this.usage;
  }

  /**
   * Returns the current power.
   * 
   * @return the current power
   */
  public double getPwrReading() {
    return pwrReading;
  }

  /**
   * Returns the description of this command.
   * 
   * @return a description of this command
   */
  @Override
  public String getDescription() {
    return this.description;
  }

  /**
   * Initialize the SourceData with the power data obtained from the client.
   * 
   * @param name The name of the tower or lounge to get data from
   * @return Whether or not the data was successfully initialized
   */
  public boolean initializeData(String name) {
    try {
      long dTime;
      SimpleDateFormat format = new SimpleDateFormat("yyyy-MMM-dd kk:mm:ss", Locale.US);
      Source source;
      XMLGregorianCalendar timestamp;
      source = client.getSource(name);
      timestamp = client.getLatestSensorData(name).getTimestamp();
      dataModule = new SourceData(source.getName());
      dataModule.setPowerConsumed(client.getPowerConsumed(source.getName(), timestamp));
      pwrReading = dataModule.getPowerConsumed();
      dTime = timestamp.toGregorianCalendar().getTimeInMillis();
      dataModule.setTime(format.format(dTime));
      return true;
    }
    catch (NotAuthorizedException e) {
      System.out.format("You are not authorized to view %s", name);
      return false;
    }
    catch (ResourceNotFoundException e) {
      System.out.format("The tower or lounge %s is invalid "
          + "(Enter \"help\" to see available sources", name);
      return false;
    }
    catch (BadXmlException e) {
      System.out.format("Bad XML: %s", e.getMessage());
      return false;
    }
    catch (MiscClientException e) {
      System.out.format("Unknown error has occurred: %s", e.getMessage());
      return false;
    }
  }

  /**
   * Prints the results of executing this command.
   */
  @Override
  public void printResults() {
    if (!initializeData(this.input)) {
      return;
    }
    System.out.format("%s %s %s %s %s %s", dataModule.getName(), "'s power as of",
        dataModule.getTime(), "was ", (int) dataModule.getPowerConsumed() / 1000, "kW");
  }

  // public static void main(String[] args) {
  // CurrentPower cp = new CurrentPower();
  // String[] arg = { "current-power", "Ilima-A" };
  // WattDepotClient cl = new WattDepotClient(args[0]);
  // if (cp.initializeCommand(cl, arg)) {
  // if (cp.initializeData(arg[1])) {
  // cp.printResults();
  // }
  // }

  // }

}